const mysql = require('mysql2/promise');


class Database {
  constructor(config) {
    this.pool = mysql.createPool(config);
  }

  async connect() {
    try {
      const connection = await this.pool.getConnection();
      console.log('Connected to MySQL database.');
      return connection;
    } catch (error) {
      console.error('Error connecting to MySQL:', error.message);
      throw error;
    }
  }

  async disconnect(connection) {
    try {
      await connection.release();
      console.log('Disconnected from MySQL database.');
    } catch (error) {
      console.error('Error disconnecting from MySQL:', error.message);
      throw error;
    }
  }

  async query(sql, values = []) {
    try {
      const [rows, fields] = await this.pool.execute(sql, values);
      return rows;
    } catch (error) {
      console.error('Error executing query:', error.message);
      throw error;
    }
  }

  async get(sql, values = []) {
    try {
      const [row] = await this.pool.query(sql, values);
      return row[0];
    } catch (error) {
      console.error('Error executing query:', error.message);
      throw error;
    }
  }

  async insert(sql, values = []) {
    try {
      const [result] = await this.pool.execute(sql, values);
      return result.insertId;
    } catch (error) {
      console.error('Error executing insert query:', error.message);
      throw error;
    }
  }

  async update(sql, values = []) {
    try {
      const [result] = await this.pool.execute(sql, values);
      return result.affectedRows;
    } catch (error) {
      console.error('Error executing update query:', error.message);
      throw error;
    }
  }

  async delete(sql, values = []) {
    try {
      const [result] = await this.pool.execute(sql, values);
      return result.affectedRows;
    } catch (error) {
      console.error('Error executing delete query:', error.message);
      throw error;
    }
  }
}

module.exports = Database;
